# coding:utf-8
import threading
import os
import socket
import logging

import parse_config
import utils

class SyncClient(threading.Thread):
    def __init__(self, sync_id, path, file,  **kwargs):
        threading.Thread.__init__(self, **kwargs)
        self.setDaemon(1)
        self.sync_id = sync_id
        self.full_file = os.path.join(path, file)
        self.file = file
        if os.path.sep != '/':
            self.file = self.file.replace(os.path.sep, '/')
        self.proxy = parse_config.parse_proxy_config()
        self.logger = logging.getLogger('sync')

    def run(self):
        content = ''
        try:
            fp = open(self.full_file)
            content = fp.read()
        finally:
            fp.close()
            
        head = "\r\n".join([self.sync_id, self.file, ''])
        data_len = len(head) + len(content)
        head = ('%-8d' % data_len) + head
        
        self.logger.info('try sync %s' % self.full_file)
        try:
            status = self.sync(head, content)
            self.logger.info('sync %s %s' % (self.full_file, status))
        except:
            self.logger.error('sync %s error' % self.full_file)
        

    def sync(self, head, content):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            sock.connect(self.proxy)
            # head先发送，如果sync_id未注册，proxy直接就拒绝了
            while len(head) > 0:
                sent_bytes = sock.send(head)
                head = head[sent_bytes:]
            # content的内容可能还有中文，不能和head拼接之后再发送
            while len(content) > 0:
                sent_bytes = sock.send(content)
                content = content[sent_bytes:]
                
            return sock.recv(1024)
        except Exception, e:
            print e
            raise e
        finally:
            sock.close()        

if __name__ == '__main__':
    print repr('\r\n'.join(['a', 'b', '']))